//
//  NeedishLogin.m
//  iNeedish
//
//  Created by Tobias Rundström on 2009-11-06.
//  Copyright 2009 Purple Scout. All rights reserved.
//

#import "NeedishLogin.h"
#import "GTMNSDictionary+URLArguments.h"
#import "NSData+Base64.h"
#import "JSON.h"


@implementation NeedishLogin

@synthesize delegate = _delegate;

+(id)loginWithUsername:(NSString*)username andPassword:(NSString*)password
{
	self = [super alloc];
	
	
	NSString *path = @"/users/authenticate.json";
	NSString *host = @"http://api.needish.com";
	NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
								@"95c84893b0e2b86fc08eef6e6d5d63ac", @"api_key", // I am providing my own API key as a convenience because I'm trusting you not to use it for evil.
								nil];		
	
	NSURL *url = [NSURL URLWithString:[host stringByAppendingFormat:@"%@?%@", path, [parameters gtm_httpArgumentsString]]];
	TTLOG(@"Login at URL: %@", url);
	
	/* Remove all cookies, we want new ones */
	NSHTTPCookieStorage *store = [NSHTTPCookieStorage sharedHTTPCookieStorage];
	NSArray *cookies = [store cookiesForURL:url];
	for (NSHTTPCookie *c in cookies) {
		TTLOG(@"Removing cookie %@", [c name]);
		[store deleteCookie:c];
	}
	
	
	NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
	
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	[request setValue:authValue forHTTPHeaderField:@"Authorization"];

	NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
	[connection start];
	
	return [self autorelease];
}



-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	if (_responseData) {
		[_responseData appendData:data];
	} else {
		_responseData = [data mutableCopy];
	}
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[_delegate loginDidFailWithError:error];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSString *responseBody = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
	
	NSDictionary *json = [responseBody JSONValue];
    NSDictionary *root = [json objectForKey:@"rsp"];
	
	NSNumber *num = [[root objectForKey:@"status"] objectForKey:@"code"];
	NSNumber *userid = [[[root objectForKey:@"user"] objectForKey:@"User"] objectForKey:@"id"];

	[responseBody release];
	_responseData = nil;
	
	if (userid) {
		TTLOG(@"Cool, we managed to login!");
		[_delegate loginDidSucceed];
	} else {
		if (num) {
			NSDictionary *errDict = [NSDictionary dictionaryWithObjectsAndKeys:
									 NSLocalizedString(@"Incorrect email or password.", nil), NSLocalizedDescriptionKey,
									 [NSArray arrayWithObject:NSLocalizedString(@"OK", nil)], NSLocalizedRecoveryOptionsErrorKey,
									 nil];
			NSError *err = [NSError errorWithDomain:@"ineedish" code:1 userInfo:errDict];
			[_delegate loginDidFailWithError:err];			
		}

	}
}

-(void)dealloc
{
	TTLOG(@"DEALLOC: NeedishLogin");
	[_responseData release];
	[super dealloc];
}


@end
